using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Runtime;
using System.Text;
using Test.Entity;
using Test.Interface;
using Test.Service;

namespace Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddControllers();
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();
            builder.Services.AddIdentity<User,Role>()
                .AddEntityFrameworkStores<UserAndRoleDbContext>();
            builder.Services.AddDbContext<UserAndRoleDbContext>(opt =>
            {
                string constr = builder.Configuration.GetConnectionString("Default");
                Console.WriteLine("字符连接：" + constr);
                opt.UseSqlServer(constr);
            });
            builder.Services.AddScoped<IUserAppService, UserAppService>();
            //获取jwt配置项
            //var jwtTokenConfig = builder.Configuration.GetSection("JWTTokenOption").Get<JWTTokenOption>();
            //builder.Services.AddSingleton(jwtTokenConfig);
            builder.Services.Configure<JWTTokenOption>(builder.Configuration.GetSection("JWTTokenOption"));
            builder.Services.AddScoped<IJwtHelperAppService,JwtHelperAppService>();
            builder.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
                {
                    var jwtTokenConfig = builder.Configuration.GetSection("JWTTokenOption").Get<JWTTokenOption>();
                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtTokenConfig.IssuerSigningKey));
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true, //是否验证Issuer
                        ValidIssuer = jwtTokenConfig.Issuer, //发行人Issuer
                        ValidateAudience = true, //是否验证Audience
                        ValidAudience = jwtTokenConfig.Audience,
                        ValidateIssuerSigningKey = true, //是否验证SecurityKey
                        IssuerSigningKey = key, //SecurityKey
                        ValidateLifetime = true, //是否验证失效时间
                        ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值，解决服务器端时间不同步问题（秒）
                    };
                });
            //添加Swagger的Authiozer的按钮鉴权
            builder.Services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
                s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "在下框中输入请求头中需要添加Jwt授权Token：Bearer Token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                s.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme{
                                Reference = new OpenApiReference {
                                            Type = ReferenceType.SecurityScheme,
                                            Id = "Bearer"}
                           },new string[] { }
                        }
                    });
            });

            builder.Services.AddDataProtection();
            builder.Services.AddIdentityCore<User>(opt =>
            {
                // 对密码复杂度苛刻设置
                opt.Password.RequireDigit = false;
                opt.Password.RequireLowercase = false;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = false;
                opt.Password.RequiredLength = 6;
                opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
                opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
            });
            var idBuilder = new IdentityBuilder(typeof(User), typeof(Role), builder.Services);
            idBuilder.AddEntityFrameworkStores<UserAndRoleDbContext>()
                    .AddDefaultTokenProviders()
                    .AddRoleManager<RoleManager<Role>>()
                    .AddUserManager<UserManager<User>>();


            var app = builder.Build();
            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            app.UseHttpsRedirection();
            //调用中间件：UseAuthentication（认证），必须在所有需要身份认证的中间件前调用，比如 UseAuthorization（授权）。
            app.UseAuthentication();
            app.UseAuthorization();
            app.MapControllers();
            app.Run();
        }
    }
}